package andy.ham;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import andy.ham.DaoMaster.DevOpenHelper;

public class LifeDiary extends ListActivity {

	public static final int MENU_ITEM_INSERT = Menu.FIRST;
	public static final int MENU_ITEM_DELETE = Menu.FIRST+1;

	//DAO使用的变量
	private SQLiteDatabase db;
	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private NoteDao noteDao;
	private Cursor cursor;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary_list);

		InitDAO();
		InitList();
		final SearchView searchView=(SearchView)findViewById(R.id.search);
		final Button button=(Button) findViewById(R.id.myMenu);
		registerForContextMenu(button);

		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				v.showContextMenu();
			}
		});

		searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextSubmit(String query) {
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				if(TextUtils.isEmpty(newText))
				{
					InitList();
				}
				else
				{
					String textColumn = NoteDao.Properties.Title.columnName;
					String dateColumn = NoteDao.Properties.Date.columnName;
					String selection="TITLE LIKE ?";
					String[] args={"%"+newText+"%"};
					cursor = db.query(noteDao.getTablename(),noteDao.getAllColumns(),selection,args,null,null,null);
					String[] from = { textColumn, dateColumn };
					int[] to = { R.id.text1, R.id.created };

					SimpleCursorAdapter adapter = new SimpleCursorAdapter(
							LifeDiary.this,R.layout.diary_row,cursor,from,to);
					setListAdapter(adapter);
				}
				return true;
			}
		});
	}

	//创建按钮的上下文菜单
	@Override
	public void onCreateContextMenu(ContextMenu menu,View v, ContextMenu.ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.menu,menu);
	}


	//按钮子项被选择时的相应行为
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_add:
				Intent intent0 = new Intent(this, DiaryEditor.class);
				intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
				intent0.setData(getIntent().getData());
				startActivity(intent0);
				LifeDiary.this.finish();
				cursor.requery();
				return true;
			case R.id.menu_delete:
				if(cursor.moveToPosition(0))
                {
					AlertDialog.Builder b = new AlertDialog.Builder(LifeDiary.this);
					b.setTitle("删除全部");
					b.setMessage("确认删除全部吗？");
					b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							noteDao.deleteAll();
							Toast.makeText(LifeDiary.this,R.string.diary_delete_success,Toast.LENGTH_LONG).show();
							refresh();
						}
					});
					b.setNegativeButton("取消",null);
					b.create();
					b.show();
                }
			    else
                {
                    Toast.makeText(this,R.string.diary_delete_fail,Toast.LENGTH_LONG).show();
                }
		}
		return super.onContextItemSelected(item);
	}

	public void refresh() {
		onCreate(null);
	}

	//打开名为notes-db的数据库，游标cursor为空，默认指向数据库第一行的数据
	//按照daoMaster -> daoSession -> noteDao的顺序初始化对象。
	private void InitDAO() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		noteDao = daoSession.getNoteDao();
	}

	private void InitList() {
		String textColumn = NoteDao.Properties.Title.columnName;
		String dateColumn = NoteDao.Properties.Date.columnName;
		String orderBy = dateColumn +" COLLATE LOCALIZED DESC";
		cursor = db.query(noteDao.getTablename(),noteDao.getAllColumns(),null,null,null,null,orderBy);
		String[] from = { textColumn, dateColumn };
		int[] to = { R.id.text1, R.id.created };

		//运用适配器将数据显示在ListVIew上
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.diary_row,cursor,from,to);
		setListAdapter(adapter);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MENU_ITEM_INSERT, 0, R.string.menu_insert);
		menu.add(Menu.NONE,MENU_ITEM_DELETE,0,R.string.menu_delete);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			// 插入一条数据
			case MENU_ITEM_INSERT:
				Intent intent0 = new Intent(this, DiaryEditor.class);
				intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
				intent0.setData(getIntent().getData());
				startActivity(intent0);
				LifeDiary.this.finish();
				cursor.requery();
				return true;
			case MENU_ITEM_DELETE:
				if(cursor.moveToPosition(0))
				{
					AlertDialog.Builder b = new AlertDialog.Builder(LifeDiary.this);
					b.setTitle("删除全部");
					b.setMessage("确认删除全部吗？");
					b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							noteDao.deleteAll();
							Toast.makeText(LifeDiary.this,R.string.diary_delete_success,Toast.LENGTH_LONG).show();
							refresh();
						}
					});
					b.setNegativeButton("取消",null);
					b.create();
					b.show();
				}
				else
				{
					Toast.makeText(this,R.string.diary_delete_fail,Toast.LENGTH_LONG).show();
				}
		}
		return super.onOptionsItemSelected(item);
	}


	protected void onListItemClick(ListView l, View v, int position, long id) {

		String mid = Long.toString(id);
		Log.d("id", mid);
		Intent intent = new Intent(this, myView.class);
		Bundle bundle = new Bundle();
		bundle.putLong("id", id);
		intent.putExtras(bundle);
		Log.d("id", mid);
		startActivity(intent);
		LifeDiary.this.finish();
		cursor.requery();
	}

	protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
		cursor.requery();
		super.onActivityResult(requestCode, resultCode, intent);
	}
}
